<template>
  <div>
    <!-- 面包屑导航区域 -->
    <el-breadcrumb>
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>参数列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片展示区域 -->
    <el-card>
      <!-- 警告区域 -->
      <el-alert
        title="注意:只允许为第三级分类设置相关参数！"
        type="warning"
        :closable="false"
        show-icon
      >
      </el-alert>

      <!-- 选择商品分类区域 -->

      <el-row class="cat_opt">
        请选择商品分类：
        <!-- 商品分类级联选择框 -->
        <el-cascader
          expand-trigger="hover"
          v-model="selectedCateKeys"
          :options="cateList"
          :props="catProps"
          @change="handleChange"
        ></el-cascader>
      </el-row>
      <!-- 展示切换页 -->
      <el-tabs v-model="activeName" @tab-click="handleClick">
        <el-tab-pane label="动态参数" name="many" :disabled="isDisab">
          <!-- 添加动态参数 -->
          <el-button
            size="mini"
            type="primary"
            class="cat_opt2"
            @click="addDialogVisible = true"
            :disabled="isDisab"
            >添加参数</el-button
          >
          <!-- 添加动态表格 -->
          <el-table :data="manyTableData" border stripe>
            <!-- 展开行 -->
            <el-table-column type="expand">
              <template slot-scope="scope">
                <!-- 循环渲染tag标签 -->
                <el-tag
                  v-for="(item, i) in scope.row.attr_vals"
                  :key="i"
                  closable
                  @close="handleClose(i, scope.row)"
                >
                  {{ item }}
                </el-tag>
                <!-- 输入的文本框 -->
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model.trim="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                >
                </el-input>
                <!-- 添加的tag标签 -->
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(scope.row)"
                  >+ New Tag</el-button
                >
              </template>
            </el-table-column>
            <!-- 索引列 -->
            <el-table-column type="index" label="#"> </el-table-column>

            <el-table-column label="参数名称" prop="attr_name">
            </el-table-column>
            <!-- 操作区域 -->
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button
                  type="primary"
                  icon="el-icon-edit"
                  size="mini"
                  @click="showEditDialog(scope.row.attr_id)"
                  >编辑</el-button
                >
                <el-button
                  type="danger"
                  icon="el-icon-delete"
                  size="mini"
                  @click="removePrimary(scope.row.attr_id)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <el-tab-pane label="静态属性" name="only" :disabled="isDisab">
          <!-- 添加静态属性 -->
          <el-button
            class="cat_opt2"
            size="mini"
            type="primary"
            :disabled="isDisab"
            @click="addDialogVisible = true"
            >添加属性</el-button
          >
          <!-- 静态属性表格 -->
          <el-table :data="onlyTableData" border stripe>
            <!-- 展开行 -->
            <el-table-column type="expand">
              <template slot-scope="scope">
                <!-- 循环渲染tag标签 -->
                <el-tag
                  v-for="(item, i) in scope.row.attr_vals"
                  :key="i"
                  closable
                  @close="handleClose(i, scope.row)"
                >
                  {{ item }}
                </el-tag>
                <!-- 输入的文本框 -->
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model.trim="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                >
                </el-input>
                <!-- 添加的tag标签 -->
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(scope.row)"
                  >+ New Tag</el-button
                >
              </template>
            </el-table-column>
            <!-- 索引列 -->
            <el-table-column type="index" label="#"> </el-table-column>

            <el-table-column label="属性名称" prop="attr_name">
            </el-table-column>
            <!-- 操作区域 -->
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button
                  type="primary"
                  icon="el-icon-edit"
                  size="mini"
                  @click="showEditDialog(scope.row.attr_id)"
                  >编辑</el-button
                >
                <el-button
                  type="danger"
                  icon="el-icon-delete"
                  size="mini"
                  @click="removePrimary(scope.row.attr_id)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-card>

    <!-- 添加参数的对话框  公共部分提取-->
    <el-dialog
      :title="'添加' + titleText"
      :visible.sync="addDialogVisible"
      width="50%"
      @close="addDialogClose"
    >
      <!-- 展示区域 -->
      <el-form
        :model="addForm"
        :rules="addFormRules"
        ref="addFormRef"
        label-width="100px"
      >
        <el-form-item :label="titleText" prop="attr_name">
          <el-input v-model="addForm.attr_name"></el-input>
        </el-form-item>
      </el-form>

      <!-- 操作区域 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addParams">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 修改参数的对话框  公共部分提取-->
    <el-dialog
      :title="'修改' + titleText"
      :visible.sync="editDialogVisible"
      width="50%"
      @close="editDialogClose"
    >
      <!-- 展示区域 -->
      <el-form
        :model="editForm"
        :rules="editFormRules"
        ref="editFormRef"
        label-width="100px"
      >
        <el-form-item :label="titleText" prop="attr_name">
          <el-input v-model="editForm.attr_name"></el-input>
        </el-form-item>
      </el-form>

      <!-- 操作区域 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editParams">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
// 这里可以导入其他文件（比如：组件，工具js，第三方插件js，json文件，图片文件等等）

export default {
  components: {},
  // 定义属性
  data() {
    return {
      // 获取到的分类列表
      cateList: [],
      // 级联选择框的配置对象
      catProps: {
        value: 'cat_id',
        label: 'cat_name',
        children: 'children',
      },
      // 级联双向数据绑定到的数组
      selectedCateKeys: [],
      // 切换展示区域
      activeName: 'many',
      //动态参数
      manyTableData: [],
      // 静态参数
      onlyTableData: [],
      // 添加属性对话框控制属性
      addDialogVisible: false,
      // 表单数据
      addForm: {
        attr_name: '',
      },
      // 添加表单验证规则
      addFormRules: {
        attr_name: [
          { required: true, message: '请输入参数名称', trigger: 'blur' },
        ],
      },
      // 修改参数表单
      editForm: {
        attr_name: '',
      },
      // 修改参数表单验证规则
      editFormRules: {
        attr_name: [
          { required: true, message: '请输入参数名称', trigger: 'blur' },
        ],
      },
      // 修改对话框
      editDialogVisible: false,
    };
  },
  // 生命周期 - 创建完成（可以访问当前this实例）
  created() {
    this.getCateList();
  },
  // 计算属性，会监听依赖属性值随之变化
  computed: {
    isDisab: function () {
      return this.selectedCateKeys.length !== 3 ? true : false;
    },
    getCateId: function () {
      if (this.selectedCateKeys.length === 3) {
        return this.selectedCateKeys[2];
      }
      return null;
    },
    titleText: function () {
      return this.activeName === 'many' ? '动态属性' : '静态参数';
    },
  },
  // 监控data中的数据变化
  watch: {},
  // 方法集合
  methods: {
    // 获取商品分类列表
    async getCateList() {
      const { data: res } = await this.$http.get('categories');
      if (res.meta.status !== 200)
        return this.$message.error('获取商品列表失败!');
      this.cateList = res.data;
    },
    //级联选择框变动会触发
    handleChange() {
      this.getParamsData();
    },
    //  列表切换展示页
    handleClick() {
      this.getParamsData();
    },
    // 根据3级id 获取参数详情
    async getParamsData() {
      // 只选择三级分类处理
      if (this.selectedCateKeys.length !== 3) {
        this.selectedCateKeys = [];
        this.manyTableData = [];
        this.onlyTableData = [];
        return;
      }
      // 切换时根据ID获取其具体信息
      const { data: res } = await this.$http.get(
        `categories/${this.getCateId}/attributes`,
        {
          params: { sel: this.activeName },
        }
      );
      res.data.forEach((item) => {
        item.attr_vals = item.attr_vals.split(' ');
        item.inputVisible = false;
        item.inputValue = '';
      });
      if (res.meta.status !== 200)
        return this.$message.error('获取' + this.activeName + '失败！');
      this.activeName === 'many'
        ? (this.manyTableData = res.data)
        : (this.onlyTableData = res.data);
    },
    // 监听添加对话框关闭事件
    addDialogClose() {
      this.$refs.addFormRef.resetFields();
    },
    //点击按钮 ，请求参数
    addParams() {
      this.$refs.addFormRef.validate(async (valid) => {
        if (!valid) return;
        const { data: res } = await this.$http.post(
          `categories/${this.getCateId}/attributes`,
          {
            attr_name: this.addForm.attr_name,
            attr_sel: this.activeName,
          }
        );
        if (res.meta.status !== 201) return this.$message.error('添加失败！');
        this.$message.success('添加成功！');
        this.addDialogVisible = false;
        this.getParamsData();
      });
    },
    // 监听编辑参数对话框
    async showEditDialog(attr_id) {
      //查询当前参数的信息
      const { data: res } = await this.$http.get(
        `categories/${this.getCateId}/attributes/${attr_id}`,
        {
          params: { attr_sel: this.activeName },
        }
      );
      if (res.meta.status !== 200) {
        return this.$message.error('获取参数信息失败 ！');
      }
      this.editForm = res.data;
      this.editDialogVisible = true;
    },
    // 重置修改表单
    editDialogClose() {
      this.$refs.editFormRef.resetFields();
    },
    // 点击后提交修改请求
    editParams() {
      // 表单预验证
      this.$refs.editFormRef.validate(async (valid) => {
        if (!valid) return;
        console.log(this.activeName);
        const { data: res } = await this.$http.put(
          `categories/${this.getCateId}/attributes/${this.editForm.attr_id}`,
          {
            attr_sel: this.activeName,
            attr_name: this.editForm.attr_name,
          }
        );
        if (res.meta.status !== 200) {
          return this.$message.error('修改参数失败 !');
        }
        this.$message.success('修改参数成功 !');
        this.getParamsData();
        this.editDialogVisible = false;
      });
    },
    //删除参数
    async removePrimary(attr_id) {
      let confimResult = await this.$confirm(
        '此操作将永久删除该参数, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }
      ).catch((err) => err);
      // 取消操作
      if (confimResult !== 'confirm') {
        return this.$message.info('已取消删除');
      }
      // 确定则删除该参数
      const { data: res } = await this.$http.delete(
        `categories/${this.getCateId}/attributes/${attr_id}`
      );
      if (res.meta.status !== 200) {
        return this.$message.error('删除参数失败 ！');
      }
      this.$message.success('删除参数成功 !');
      this.getParamsData();
    },
    // 监听文本框失去焦点或者键盘按下事件
    async handleInputConfirm(row) {
      // 优化 去除收尾空格无效输入
      if (row.inputValue === '') {
        row.inputValue = '';
        row.inputVisible = false;
        return;
      }
      //  有有效输入 给字段添加输入的内容
      row.attr_vals.push(row.inputValue);
      // 添加完成则 row.inputValue的值就没用了清空
      row.inputValue = '';
      // 清空后隐藏
      row.inputVisible = false;
      this.saveAttrId(row);
    },
    // 修改参数公共代码抽离 保存删除的数据
    async saveAttrId(row) {
      const { data: res } = await this.$http.put(
        `categories/${this.getCateId}/attributes/${row.attr_id}`,
        {
          attr_name: row.attr_name,
          attr_sel: row.attr_sel,
          attr_vals: row.attr_vals.join(' '),
        }
      );
      if (res.meta.status !== 200)
        return this.$message.error('设置参数失败 ！');
      this.$message.success('设置参数成功 ！');
    },
    // 点击按钮触发文本输入框
    showInput(row) {
      row.inputVisible = true;
      //让文本框自动获得焦点
      /**
       * $nextTick（）的作用：当页面的元素被
       * 重新渲染的时候才会执行指定的回调函数的代码
       */
      this.$nextTick(() => {
        this.$refs.saveTagInput.$refs.input.focus();
      });
    },
    //删除对应的tag参数可选项
    handleClose(i, row) {
      row.attr_vals.splice(i, 1);
      this.saveAttrId(row);
    },
  },

  // 生命周期 - 挂载完成（可以访问DOM元素）
  mounted() {},
};
</script>

<style lang='less' scoped>
.cat_opt {
  margin: 15px 0;
}
.cat_opt2 {
  margin-bottom: 20px;
}
.el-tag {
  margin: 10px;
}
.input-new-tag {
  width: 120px;
  margin: 10px;
}
</style>